package cn.ac.siom.query.action;

import cn.ac.siom.query.service.IMediaService;
import cn.ac.siom.query.util.action.DefaultAction;
import cn.ac.siom.query.vo.Media;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Controller
@RequestMapping({"/home/*"})
public class MediaAction extends DefaultAction{
    @Resource
    private IMediaService mediaService;
    @Autowired
    private Config config;

    @ResponseBody
    @RequestMapping(value={"findPage_Media"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}, produces={"application/json;charset=UTF-8"})
    public Map findPage(Integer type, Integer rownum, Integer page_id, HttpServletRequest request, HttpServletResponse response) throws SQLException {
        insertAccessinfo(request,"在线视频");
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<Media> medias = this.mediaService.list_page(type, rownum, page_id);
        Integer count = this.mediaService.list_count(type);
        for (Media media : medias) {
            String host_port_path_images = config.Image_path_images;
            String host_port_path_videos =  config.Image_path_videoes;
            if (media.getType() == 1) {
                media.setRs_address(host_port_path_images + media.getRs_address());
            } else {
                media.setRs_address(host_port_path_videos + media.getRs_address());
            }
        }
        Map map = new HashMap();
        map.put("data",medias);
        map.put("count", count);
        map.put("page_id",page_id);
        return map;
    }

    @RequestMapping({"media_insert"})
    public void insert(Media vo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String sqlPath = null;
        String localPath_images = request.getSession().getServletContext().getRealPath("/media/images/");
        String localPath_videoes = request.getSession().getServletContext().getRealPath("/media/videoes/");
        String filename = null;
        if (!vo.getFile().isEmpty()) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String contentType = vo.getFile().getContentType();
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            filename = uuid + "." + suffixName;
            logger.info(filename+"============================="+contentType);
            if ((suffixName.contains("jpeg")) || (suffixName.contains("gif")) || (suffixName.contains("bmp")) || (suffixName.contains("png")) || (suffixName.contains("jpg"))) {
                vo.getFile().transferTo(new File(localPath_images + File.separator  + filename));
                vo.setType(Integer.valueOf(1));
            } else {
                vo.getFile().transferTo(new File(localPath_videoes + File.separator  + filename));
                vo.setType(Integer.valueOf(2));
            }
        }
        sqlPath = filename;
        vo.setRs_address(sqlPath);
        vo.setStatus(Integer.valueOf(1));

        try {
            if (this.mediaService.insert(vo)) {
                super.print(response, "success");
            } else {
                super.print(response, "failure");
            }
        } catch (Exception e) {
            e.printStackTrace();
            super.print(response, "failure");
        }
    }

    @RequestMapping({"Media_update"})
    public void update(HttpServletResponse response, Media vo, HttpServletRequest request)
            throws IOException {
        String sqlPath = null;
        String localPath_images = request.getSession().getServletContext().getRealPath("/media/images/");
        String localPath_videoes = request.getSession().getServletContext().getRealPath("/media/videoes/");
        String filename = null;
        if (vo.getFile() != null) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String contentType = vo.getFile().getContentType();
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            filename = uuid + "." + suffixName;
            if ((suffixName.contains("jpeg")) || (suffixName.contains("gif")) || (suffixName.contains("bmp")) || (suffixName.contains("png")) || (suffixName.contains("jpg"))) {
                vo.getFile().transferTo(new File(localPath_images + File.separator  + filename));
                vo.setType(Integer.valueOf(1));
            }
            else {
                vo.getFile().transferTo(new File(localPath_videoes + File.separator  + filename));
                vo.setType(Integer.valueOf(2));
            }
        }
        sqlPath = filename;
        vo.setRs_address(sqlPath);
        try {
            if (this.mediaService.update(vo)) {
                super.print(response, "success");
            } else {
                super.print(response, "failure");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            super.print(response, "failure");
        }
    }

    @RequestMapping({"media_delete"})
    public void delete(HttpServletResponse response, HttpServletRequest request, Media vo) {
        try {
            String[] result = request.getParameter("ids").split("\\|");
            List<String> all = new ArrayList();
            for (int x = 0; x < result.length; x++) {
                all.add(result[x]);
            }
            if (all.size() > 0) {
                String localPath_images = request.getSession().getServletContext().getRealPath("/media/images/");
                File file2 = new File(localPath_images + File.separator + vo.getRs_address());
                if (file2.exists()) {
                     Boolean.valueOf(file2.delete());
                }
                super.print(response, Boolean.valueOf(this.mediaService.delete(all)));
            } else {
                super.print(response, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            super.print(response, false);
        }
    }

    @ResponseBody
    @RequestMapping(value={"findNO_Media"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}, produces={"application/json;charset=UTF-8"})
    public Media findNO(HttpServletRequest request, Integer id) throws SQLException {
        insertAccessinfo(request,"视频详情");
        Media media = this.mediaService.list_one(id);
        if (media.getType() == 1) {
            media.setRs_address(this.config.Image_path_images + media.getRs_address());
        } else {
            media.setRs_address(this.config.Image_path_videoes + media.getRs_address());
        }
        return media;
    }

    @ResponseBody
    @RequestMapping(value={"findPage_Media_Images"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}, produces={"application/json;charset=UTF-8"})
    public List<Map> findPageAll(HttpServletRequest request, Integer type, Integer rownum, Integer page_id) throws SQLException {
        insertAccessinfo(request,"最新图片视频");
        List<Media> medias = this.mediaService.list_pageAll(rownum, page_id);
        List<Map> list = new ArrayList();
        Integer cont = this.mediaService.list_countAll();
        for (Media media : medias) {
            Map map = new HashMap();
            if (media.getType() == 1) {
                map.put("sr_address", this.config.Image_path_images + media.getRs_address());
            } else {
                map.put("sr_address", this.config.Image_path_videoes + media.getRs_address());
            }
            Integer id = media.getId();
            String name = media.getName();
            String summary = media.getSummary();
            Date createDate = media.getCreatetime();
            Date update = media.getUpdatetime();
            map.put("type", type);
            map.put("id", id);
            map.put("name", name);
            map.put("summary", summary);
            map.put("createDate", createDate);
            map.put("update", update);
            map.put("cont", cont);
            list.add(map);
        }
        return list;
    }

    @ResponseBody
    @RequestMapping(value={"find_photo"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}, produces={"application/json;charset=UTF-8"})
    public List findPhoto(HttpServletRequest request, HttpServletResponse response)throws SQLException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        insertAccessinfo(request,"主题图片");
        return this.mediaService.list_photo();
    }

    public String getText()
    {
        return null;
    }
}